<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    const createStore = (reducer) => {
      // 定义一个初始的state
      let state = null;
      // getState用于获取状态
      const getState = () => state;

      // 定义一个监听器，用于管理一些方法
      const listeners = [];
      const subscribe = (listener) => listeners.push(listener);

      // 定义一个dispatch方法，让每次有action传入的时候返回reducer执行之后的结果
      const dispatch = (action) => {
        // 调用reducer来处理数据
        state = reducer(state, action);
        // 让监听器里的所有方法运行
        listeners.forEach((listener) => listener());
      };
      //  初始化state
      dispatch({});
      return {
        getState,
        dispatch,
        subscribe,
      };
    };
    // 定义一个计数器的状态
    const countState = {
      count: 10,
    };
    // 定一个方法叫changeState，用于处理state的数据，每次都返回一个新的re状态
    const changeState = (state, action) => {
      // 如果state是null, 就返回countState
      if (!state) return countState;
      switch (action.type) {
        // 处理减
        case "COUNT_DECREMENT":
          return {
            ...state,
            count: state.count - action.number,
          };
        // 处理加
        case "COUNT_INCREMENT":
          return {
            ...state,
            count: state.count + action.number,
          };
        default:
          return state;
      }
    };
    // 创建一个store
    const store = createStore(changeState);
    console.log(store.getState());
  </script>
</html>
